package cn.lee.share.utils;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import cn.lee.TomcatConstants;
import freemarker.template.TemplateException;

public class VelocityUtils {
    private static final String templateFolder = TomcatConstants.WEB_ROOT + File.separator + "templates";
    public static void runTemplate(Map rootData, String templateStr, Writer out) throws IOException, TemplateException{
        /* Create and adjust the configuration */ 
        Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templateFolder);
        Velocity.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        Velocity.init();
        VelocityContext context = new VelocityContext();
        Template template = Velocity.getTemplate(templateStr);
        Iterator it = rootData.entrySet().iterator();
        while(it.hasNext()){
            Entry e = (Entry) it.next();
            context.put((String)e.getKey(), e.getValue());
        }
        template.merge(context, out);
        out.flush(); 
    }
}
